package com.qding.park.adapter.report.valid;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Path;
import javax.validation.Path.Node;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.qding.park.adapter.report.exception.ValidateException;

public class ValidateUtil {
    
    private static Validator validator; // 它是线程安全的 
    
    static { 
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); 
        validator = factory.getValidator(); 
    } 
     
    public static <T> void validate(T t,String msg) { 
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(t); 
        
        if(constraintViolations.size() > 0) { 
            Map<String,String> fieldError =new HashMap<String,String>(); 
            for(ConstraintViolation<T> constraintViolation: constraintViolations) { 
                Path propertyPath=constraintViolation.getPropertyPath();
                fieldError.put(propertyPath.toString(), constraintViolation.getMessage() );
//                Iterator<Node>  nodeInter= propertyPath.iterator();
//                while(nodeInter.hasNext()){
//                    Node node=nodeInter.next();
//                    fieldError.put(node.getName(), constraintViolation.getMessage() );
//                }
               
            } 
            throw new ValidateException(fieldError,msg); 
        } 
    } 

}
